﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Windows.Browser;
using C1.Silverlight;

namespace ControlExplorer
{
    public partial class HomePage : Page
    {
        public HomePage()
        {
            InitializeComponent();

            DataContext = MainViewModel.Instance;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var currentSource = NavigationService.CurrentSource;
        }

        private void favoritesPanel_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.NewSize.Width > 0 && e.NewSize.Height > 0)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    InitializeFavorites();
                });
            }
        }

        private void InitializeFavorites()
        {
            var favorites = MainViewModel.Instance.Controls.Where(c => c.IsFavorite);
            var favoritesEnumerator = favorites.GetEnumerator();

            double width = favoritesPanel.ActualWidth;
            int columnsCount = Math.Max(1, (int)Math.Floor(width / favoritesPanel.ItemWidth));
            favoritesPanel.Children.Clear();
            var randSpaces = new Random(2);
            var randGrays = new Random(1);
            var previousEmptyColumn = 0;
            var previousGrayColumn = 0;
            bool end = false;
            int randNex = columnsCount - 1;
            if (columnsCount == 3)
            {
                // add less rectangles for 3 columns
                randNex = 7;
            }
            for (int i = 0; !end; i++)
            {
                if (end)
                {
                    break;
                }
                // don't add rectangles if there are less than 3 columns
                var emptyColumnIndex = (i == 0 || columnsCount <= 2) ? -1 : randSpaces.Next(randNex);
                if (emptyColumnIndex == previousEmptyColumn)
                {
                    emptyColumnIndex++;
                }
                var grayColumnIndex = (columnsCount <= 2) ? -1 : randGrays.Next(randNex + 1);
                if (grayColumnIndex == previousGrayColumn)
                {
                    grayColumnIndex++;
                }
                for (int j = 0; j < columnsCount; j++)
                {
                    if (!end && emptyColumnIndex == j)
                    {
                        favoritesPanel.Children.Add(new Rectangle());
                    }
                    else if (!end && grayColumnIndex == j)
                    {
                        Rectangle rc = new Rectangle();
                        try
                        {
                            rc.Fill = Application.Current.Resources["IconGrayBackground"] as Brush;
                            rc.Height = rc.Width = 76;
                            rc.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                            rc.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        }
                        catch
                        {
                        }
                        favoritesPanel.Children.Add(rc);
                    }
                    else
                    {
                        end = !favoritesEnumerator.MoveNext();
                        if (end)
                        {
                            favoritesPanel.Children.Add(new Rectangle());
                        }
                        else
                        {
                            var control = favoritesEnumerator.Current;
                            var icon = favoritesEnumerator.Current.Icon;
                            var tile = new TileControl
                            {
                                Tag = control,
                                IconTemplate = control.Icon,
                                Title = control.Name,
                                Margin = new Thickness(0),
                            };
                            tile.Click += new EventHandler(tile_Click);
                            favoritesPanel.Children.Add(tile);
                        }
                    }

                }
                if (emptyColumnIndex >= 0)
                {
                    previousEmptyColumn = emptyColumnIndex;
                }
                if (grayColumnIndex >= 0)
                {
                    previousGrayColumn = grayColumnIndex;
                }
            }
            // clean the last row if it only contains gray and empty rectangles
            bool needCleanupLastRow = favoritesPanel.Children.Count > columnsCount;
            for (int j = favoritesPanel.Children.Count - 1; j >= favoritesPanel.Children.Count - columnsCount; j--)
            {
                if (favoritesPanel.Children[j] is TileControl)
                {
                    needCleanupLastRow = false;
                    break;
                }
            }
            if (needCleanupLastRow)
            {
                int count = favoritesPanel.Children.Count;
                for (int j = count - 1; j >= count - columnsCount; j--)
                {
                    favoritesPanel.Children.RemoveAt(j);
                }
            }
        }

        void tile_Click(object sender, EventArgs e)
        {
            var tile = sender as TileControl;
            var control = tile.Tag as ControlDescription;
            var frame = VTreeHelper.GetParentOfType(this, typeof(ControlExplorer.Frame)) as ControlExplorer.Frame;
            if (frame != null)
            {
                frame.Navigate(control.Link, frame.NavigationFrame.CurrentSource);
            }
            else
            {
                NavigationService.Navigate(control.Link);
            }
        }

        private void c1Button_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("http://www.componentone.com/"), "_new");
        }
    }
}
